package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFeign;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.ESManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ESManagerServiceImpl implements ESManagerService {

    //es模板类
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Autowired
    private ESManagerMapper esManagerMapper;

    @Override
    public void createIndexAndMapping() {
        elasticsearchTemplate.createIndex(SkuInfo.class);
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }

    @Override
    public void importAll() {
        List<Sku> skuList = skuFeign.findListBySpuId("all");
        if(skuList.size()<=0 || skuList == null){
            throw new RuntimeException("没有数据，无法导入索引库!");
        }

        //把sku -> skuInfo
        String s = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(s, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfoList) {
            String spec = skuInfo.getSpec();
            Map specMap = JSON.parseObject(spec, Map.class);
            skuInfo.setSpecMap(specMap);
        }

        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void importDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if(skuList.size()<=0 || skuList == null){
            throw new RuntimeException("没有数据，无法导入索引库!");
        }

        //把sku -> skuInfo
        String s = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(s, SkuInfo.class);

        for (SkuInfo skuInfo : skuInfoList) {
            String spec = skuInfo.getSpec();
            Map specMap = JSON.parseObject(spec, Map.class);
            skuInfo.setSpecMap(specMap);
        }
        esManagerMapper.saveAll(skuInfoList);
    }

    @Override
    public void deleteDataBySpuId(String spuId) {
        List<Sku> skuList = skuFeign.findListBySpuId(spuId);
        if(skuList.size()<=0 || skuList == null){
            throw new RuntimeException("没有数据，无法导入索引库!");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
